package com.common.boot.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.common.boot.exception.BusinessException;
import com.common.boot.mapper.SysUserMapper;
import com.common.boot.model.SysUser;
import com.common.boot.service.ISysUserService;
import com.common.boot.util.JwtUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 系统用户表 服务实现类
 * </p>
 *
 * @author jiangsong
 * @since 2024-02-26
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {
    /**
     * 默认过期时间为一天
     * 用户通过缓存最大保存会话时间为一天,每次延长30分钟，超出后需要重新获取令牌
     */
    @Value("${token.expire.time:86400000}")
    private Long expireTime;

    @Override
    public Map<String, Object> login(SysUser dto) {
        LambdaQueryWrapper<SysUser> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SysUser::getName,dto.getName());
        lambdaQueryWrapper.eq(SysUser::getPassword,dto.getPassword());
        SysUser sysUser = this.getOne(lambdaQueryWrapper);
        if(ObjectUtils.isEmpty(sysUser)){
            throw new BusinessException("您的账号密码输入有误，请检查后再输入");
        }
        Map<String, Object> map = new HashMap<>(2);
        String authorization = JwtUtil.generatorJWT(sysUser.getId(),expireTime);
        map.put("user", sysUser);
        map.put("Authorization", authorization);
        return map;
    }

    @Override
    public Map<String, Object> register(SysUser dto) {
        LambdaQueryWrapper<SysUser> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SysUser::getName,dto.getName());
        SysUser sysUser = this.getOne(lambdaQueryWrapper);
        if(!ObjectUtils.isEmpty(sysUser)){
            throw new BusinessException("账号名称重复，请重新填写账号");
        }
        Map<String, Object> map = new HashMap<>(2);
        this.save(dto);
        map.put("flag",true);
        return map;
    }
}
